import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/login.vue'
import Home from '../components/home.vue'
import Welcome from '../components/welcome.vue'
import Users from '../components/users.vue'
import Rights from '../components/power/rights.vue'
import Roles from '../components/power/roles.vue'
import GoodsCate from '../components/goods/goods_cate.vue'
import Params from '../components/goods/goods_params.vue'
import GoodsList from '../components/goods/goods_list.vue'
import AddGoods from '../components/goods/add.vue'
import Orders from '../components/order/order.vue'
import Reports from '../components/report/report.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/roles', component: Roles },
      { path: '/rights', component: Rights },
      { path: '/categories', component: GoodsCate },
      { path: '/params', component: Params },
      { path: '/goods', component: GoodsList },
      { path: '/goods/add', component: AddGoods },
      { path: '/orders', component: Orders },
      { path: '/reports', component: Reports }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 设置导航守卫
// to 将要访问得路径
// from 代表从哪个路径跳转
// next 是一个函数
router.beforeEach((to, from, next) => {
  // 判断前往地址，是首页直接放行
  if (to.path === '/login') return next()
  // 获取token值，判断是否已经登录，未登录跳转登录页，已登录则放行
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

export default router
